package com.ld.zxw.index;

import org.apache.log4j.Logger;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.NoLockFactory;

import com.ld.zxw.config.Config;
import com.ld.zxw.config.IndexFactory;
import com.ld.zxw.util.CommonUtil;

public class DeleteIndex implements IndexFactory{

	private Logger log = Logger.getLogger(DeleteIndex.class);

	@Override
	public boolean deleteAll(Config config) {
		IndexWriter  indexWriter = null;
		FSDirectory fsDirectory = null;
		try {
			fsDirectory = FSDirectory.open(config.getPath(), NoLockFactory.INSTANCE);
			indexWriter = new IndexWriter(fsDirectory, new IndexWriterConfig(config.getAnalyzer()));

			indexWriter.deleteAll();
			indexWriter.commit();
			return true;
		}catch (Exception e) {
			log.error("deletekey:",e);
			return false;
		}finally {
			CommonUtil.colseIndexWriter(indexWriter);
			CommonUtil.colseDirectory(fsDirectory);
		}
	}

	@Override
	public boolean deletekey(Config config,Term term) {
		IndexWriter  indexWriter = null;
		FSDirectory fsDirectory = null;
		try {
			fsDirectory = FSDirectory.open(config.getPath(), NoLockFactory.INSTANCE);
			indexWriter = new IndexWriter(fsDirectory, new IndexWriterConfig(config.getAnalyzer()));
			indexWriter.deleteDocuments(term);
			indexWriter.commit();
			return true;
		}catch (Exception e) {
			log.error("deletekey:",e);
			return false;
		}finally {
			CommonUtil.colseIndexWriter(indexWriter);
			CommonUtil.colseDirectory(fsDirectory);
		}
	}
	@Override
	public boolean deletekey(Config config,Query query) {
		IndexWriter  indexWriter = null;
		FSDirectory fsDirectory = null;
		try {
			fsDirectory = FSDirectory.open(config.getPath(), NoLockFactory.INSTANCE);
			indexWriter = new IndexWriter(fsDirectory, new IndexWriterConfig(config.getAnalyzer()));
			indexWriter.deleteDocuments(query);
			indexWriter.commit();
			return true;
		}catch (Exception e) {
			log.error("deletekey:",e);
			return false;
		}finally {
			CommonUtil.colseIndexWriter(indexWriter);
			CommonUtil.colseDirectory(fsDirectory);
		}
	}
}
